﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SportsStore.Domain.Abstract;
using SportsStore.Domain.Entities;

namespace SportsStore.WebUI.Controllers
{
    /// <summary>
    /// This class contains the CRUD functionality supported by Sports Store application.
    /// </summary>
    [Authorize]
    public class AdminController : Controller
    {
        private readonly IProductRepository _productRepository;

        public AdminController(IProductRepository productRepository)
        {
            _productRepository = productRepository;
        }

        public ViewResult Index()
        {
            return View(_productRepository.Products);
        }

        public ViewResult Edit(int productId)
        {
            var product = _productRepository.Products
                .Where(prod => prod.ProductID == productId)
                .FirstOrDefault();

            return View(product);
        }

        [HttpPost]
        public ActionResult Edit(Product product, HttpPostedFileWrapper image)
        {
            if (ModelState.IsValid)
            {
                if (image != null)
                {
                    product.ImageMimeType = image.ContentType;
                    product.ImageData = new byte[image.ContentLength];
                    image.InputStream.Read(product.ImageData, 0, image.ContentLength);
                }

                _productRepository.SaveProduct(product);
                TempData["message"] = string.Format("{0} has been added.", product.Name);

                return RedirectToAction("Index");
            }

            return View(product);
        }

        public ViewResult Create()
        {
            return View("Edit", new Product());
        }

        [HttpPost]
        public ActionResult Delete(int productId)
        {
            var product = _productRepository.Products
                .Where(prod => prod.ProductID == productId)
                .FirstOrDefault();

            if (product != null)
            {
                _productRepository.DeleteProduct(product);
                TempData["message"] = string.Format("{0} has been deleted", product.Name);
            }

            return RedirectToAction("Index");
        }
    }
}
